<?php

namespace App\Http\Controllers\Api;

use App\Http\Model\ResponseResult;
use App\Models\File;
use Auth;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Image;
use Storage;

class UploadController extends Controller
{
    public function __construct()
    {
        $this->middleware('api-auth')->except('readImage');
    }

    public function uploadImage(Request $request)
    {
        $this->validator($request, ['file' => 'required|file|image']);
        $file = $request->file('file');
        return ResponseResult::success(File::createFile($file, Auth::id())->url);
    }

    public function readImage($md5, Request $request)
    {
        $file = File::whereMd5($md5)->first();
        if (empty($file)) {
            try {
                $img = Image::make(Storage::disk('public')->get('404.png'))->resize(300, 300);
            } catch (FileNotFoundException $e) {
                return response('', 404);
            }
        } else {
            try {
                $img = Image::make(Storage::disk($file->engine)->get($file->path));
            } catch (FileNotFoundException $e) {
                return response('', 404);
            }
        }

        $width= $img->getWidth();
        $height = $img->getHeight();
        if ($request->has('w') && $request->has('h')) {
            $width = (int)$request->get('w', 0);
            $height = (int)$request->get('h', 0);
        }
        if ($request->has('scale')) {
            $scale = (int)$request->get('scale', 100);
            if ($scale === 0) {
                $scale = 100;
            }
            $width = ceil($width * $scale / 100);
            $height = ceil($height * $scale / 100);
        }
        $img->resize($width, $height);
        return $img->response($file->extension);
    }
}
